package top.hypnos.bigdata.filesystem.command;

import top.hypnos.bigdata.filesystem.Command;
import top.hypnos.bigdata.filesystem.MemDataNode;
import top.hypnos.bigdata.filesystem.MemDataTree;

/**
 * 创建节点
 */
public class CreateNodeCommandExecutor implements CommandExecutor {

    private MemDataNode node;

    @Override
    public void preExecute(final MemDataTree dataTree, final Command command) throws CommandException {
        final var parentPath = getParent(command.getPath());
        final var parentNode = dataTree.getNode(parentPath);
        if (parentNode == null) {
            throw new CommandException("父节点[" + parentPath + "]不存在。");
        }
        final var node = new MemDataNode();
        node.setTxnId(command.getTxnId());
        node.setPath(getLeafPath(command.getPath()));
        node.setData(command.getData());
        node.setParent(parentNode);
        this.node = node;
    }

    @Override
    public void commit() {
        node.getParent().getChildren().add(node);
    }

    @Override
    public MemDataNode getNode() {
        return this.node;
    }

    static String getParent(final String path) {
        final var end = path.lastIndexOf('/');
        return path.substring(0, end);
    }

    static String getLeafPath(final String path) {
        final var from = path.lastIndexOf('/');
        return path.substring(from + 1);
    }
}
